﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using Entities = GMAC.ReportingSystem.Business.Entities;
using System.Data;
using Components = GMAC.ReportingSystem.Business.Components;
using FrameworkManapro.Utilities;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class FieldRep : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (IsPostBack) return;
            Initialize();
            ValidateSecurity();
            
        }

        #endregion

        #region Button Events

        protected void btnNew_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var frc = new Components.FieldRepComponent();
                var FieldRep = ReadFieldRep();
                FieldRep.ID = frc.Create(FieldRep);
                var audit = new FrameworkManapro.Audit.Audit<Entities.FieldRep>
                {
                    EntityKey = FieldRep.ID.ToString(),
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Insert,
                    NewObject = FieldRep,
                    UserId = ((Entities.User)Session["User"]).UserID
                };
                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.FieldRep>(audit);
                auditDAC.InsertAudit();
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The Field Rep was successfully saved.", null);
                popupExtenderMessage.Show();
                this.PagingControl.TotalRecords = Search();
                Search();

                ClearFields();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New Field Rep", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Field Rep could not be saved", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            var frc = new  Components.FieldRepComponent();
            try
            {
                var FieldRep = ReadFieldRep();
                if (hfFR.Value.Trim() != string.Empty)
                {
                    FieldRep.ID = int.Parse(hfFR.Value);
                    var oldFieldRep = frc.GetDetails(FieldRep.ID);
                    frc.Edit(FieldRep);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.FieldRep>
                    {
                        EntityKey = FieldRep.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Update,
                        OldObject = oldFieldRep,
                        NewObject = FieldRep,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.FieldRep>(audit);
                    auditDAC.InsertAudit();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The FieldRep was successfully saved.", null);
                    popupExtenderMessage.Show();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    ClearFields();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save FieldRep", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The FieldRep couldn't be saved.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            ClearFields();
        }
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
            if (grvFieldReps != null)
            {
                if (grvFieldReps.SelectedDataKey != null)
                {
                    try
                    {
                        var FieldRepId = (int)this.grvFieldReps.SelectedDataKey.Value;
                        var frc = new Components.FieldRepComponent();
                        var FieldRep = frc.GetDetails(FieldRepId);
                        hfFR.Value = FieldRepId.ToString();
                        txtFR.Text = FieldRep.ID.ToString();
                        txtName.Text = FieldRep.Name.ToString();
                        ddlType.SelectedValue = ((int)FieldRep.Type).ToString();
                        optOptions.SelectedValue = FieldRep.Status.ToString();
                        btnSave.Visible = true;
                        btnNew.Visible = false;
                    }
                    catch (Exception ex)
                    {
                        FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify FieldRep", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                        wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the FieldRep.", ex.ToString());
                        popupExtenderMessage.Show();
                    }
                }
                else
                {
                    wucMessage.ShowMessage(UserControls.MessageType.Information, "A Field Rep must be selected.", null);
                    popupExtenderMessage.Show();
                }
            }
        }
        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (grvFieldReps.SelectedDataKey != null)
            {
                popupExtenderConfirm.Show();
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Information, "A FieldRep must be selected.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var frc = new Components.FieldRepComponent();
                if (grvFieldReps.SelectedDataKey != null)
                {
                    var FieldRepId = (int)this.grvFieldReps.SelectedDataKey.Value;
                    var FieldRep = new Entities.FieldRep { ID = FieldRepId };
                    var oldFieldRep = frc.GetDetails(FieldRep.ID);
                    frc.Delete(FieldRep);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.FieldRep>
                    {
                        EntityKey = FieldRep.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Delete,
                        OldObject = oldFieldRep,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.FieldRep>(audit);
                    auditDAC.InsertAudit();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The FieldRep was successfully deleted.", null);
                    popupExtenderMessage.Show();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete FieldRep", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The FieldRep couldn't be deleted.", ex.ToString());
                popupExtenderMessage.Show();
            }
            
        }
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            Search();
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            } 
            ClearFields();
        }
        
        #endregion

        #region Other Events

        protected void grvFieldReps_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvFieldReps, "Select$" + e.Row.RowIndex);
                if (bool.Parse((e.Row.FindControl("hfStatus") as HiddenField).Value) == true)
                {
                    e.Row.Cells[3].Text = "Active";
                }
                else
                {
                    e.Row.Cells[3].Text = "Inactive";
                }
                Entities.GeneralEnumTypes.TypeFieldRep enm = (Entities.GeneralEnumTypes.TypeFieldRep)Enum.Parse(typeof(Entities.GeneralEnumTypes.TypeFieldRep), (e.Row.FindControl("hdTypeId") as HiddenField).Value);
                e.Row.Cells[2].Text = enm.ToString().Replace('_',' ');
                

            }
        }

        private Entities.FieldRep ReadFieldRep()
        {
            var FieldRep = new  Entities.FieldRep
            {
                ID = Convert.ToInt32(txtFR.Text),
                Name = txtName.Text,
                Type = (Entities.GeneralEnumTypes.TypeFieldRep)Enum.Parse(typeof(Entities.GeneralEnumTypes.TypeFieldRep), ddlType.SelectedValue.ToString()),
                Status = bool.Parse(optOptions.SelectedValue),
           };
            
               
            return FieldRep;
        }
        #endregion

        #region Private Methods

        private void ClearFields()
        {
            txtFR.Text = string.Empty;
            txtName.Text = string.Empty;
            txtFRSearch.Text = string.Empty;
            txtNameSeach.Text = string.Empty;
            optOptions.SelectedValue = "True";
            hfFR.Value = string.Empty;
            ddlType.SelectedValue = string.Empty;
            ddlTypeSearch.SelectedValue = string.Empty;

        }
        private void Initialize()
        {
            try
            {
                foreach (int i in Enum.GetValues(typeof(Entities.GeneralEnumTypes.TypeFieldRep)))
                {
                    this.ddlType.Items.Add(new ListItem(Enum.GetName(typeof(Entities.GeneralEnumTypes.TypeFieldRep), i).ToString().Replace('_', ' '), i.ToString()));
                    this.ddlTypeSearch.Items.Add(new ListItem(Enum.GetName(typeof(Entities.GeneralEnumTypes.TypeFieldRep), i).ToString().Replace('_', ' '), i.ToString()));
                }
                this.ddlType.Items.Insert(0, new ListItem("Select...", String.Empty));
                this.ddlTypeSearch.Items.Insert(0, new ListItem("Select...", String.Empty));
                
                optOptions.SelectedValue = "True";
                btnSave.Visible = false;
                btnNew.Visible = true;
                wucMessageConfirm.ShowMessage(UserControls.MessageType.Information,
                                              "Are you sure you want to delete the selected field rep?", null);
                this.PagingControl.TotalRecords = Search();
                Search();
                
				
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }
            
        }
        private void ValidateSecurity()
        {
            var beEntities = ((Entities.User)Session["User"]).Role.Security.GetEntitySecurity("FieldRep");
            if (beEntities == null) return;
            if (!beEntities.CanRead)
            {
                grvFieldReps.Visible = false;
                btnModify.Visible = false;
                btnDelete.Visible = false;
                pnlSearch.Visible = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }
            if (!beEntities.CanInsert)
            {
                btnNew.Visible = false;
                btnCancel.Visible = false;
                pnlEdit.Visible = false;
            }
            if (!beEntities.CanDelete)
            {
                btnDelete.Visible = false;
            }
        }
        private int Search()
        {
            try
            {
                var bc = new  Components.FieldRepComponent();
                int? id = null;
                if (!string.IsNullOrEmpty(txtFRSearch.Text))
                    id = Convert.ToInt32(txtFRSearch.Text);

                string Name = txtNameSeach.Text;
                int? typeId = null;
                if (!string.IsNullOrEmpty(ddlTypeSearch.SelectedValue))
                    typeId = int.Parse(ddlTypeSearch.SelectedValue);
                FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
                paging.PageNumber = this.PagingControl.PageNumber;
                paging.PageSize = this.PagingControl.PageSize;
                paging.SortBy = this.PagingControl.SortExpression;
                paging.SortDirection = this.PagingControl.SortDirection;

               

                Entities.FieldRepCollection FieldRepcollection = bc.Search(id, Name, typeId, paging);

                grvFieldReps.DataSource = FieldRepcollection;
                grvFieldReps.DataBind();
                return FieldRepcollection.TotalResults;
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search Field Rep", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
                popupExtenderMessage.Show();
                return  0;

            }
        }

        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
             Search();
        }
        #endregion


    }
}
